from flask import Blueprint, request, jsonify
from app.models.material import Material, MaterialUsage
from app.models.user import User
from app.models.work_order import WorkOrder
from app.models import db
from app.utils.auth import require_permission, get_current_user
from datetime import datetime
from sqlalchemy import and_, or_, func

material_usage_bp = Blueprint('material_usage', __name__)

@material_usage_bp.route('', methods=['GET'])
@require_permission('material.view')
def get_usage_records():
    """获取材料使用记录列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        material_name = request.args.get('material_name', '')
        user_name = request.args.get('user_name', '')
        usage_type = request.args.get('usage_type', '')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        current_user = get_current_user()
        
        # 构建查询
        query = db.session.query(MaterialUsage).join(Material).join(User)
        
        # 权限过滤
        if current_user.role == 'user':
            query = query.filter(MaterialUsage.user_id == current_user.id)
        elif current_user.role == 'manager' and current_user.group_id:
            # 管理员只能看到自己组的使用记录
            query = query.join(WorkOrder, MaterialUsage.work_order_id == WorkOrder.id, isouter=True)
            query = query.filter(
                or_(
                    MaterialUsage.user_id == current_user.id,
                    WorkOrder.group_id == current_user.group_id,
                    MaterialUsage.work_order_id.is_(None)  # 非工单使用记录
                )
            )
        
        # 应用筛选条件
        if material_name:
            query = query.filter(Material.name.contains(material_name))
        
        if user_name:
            query = query.filter(User.username.contains(user_name))
        
        if usage_type:
            query = query.filter(MaterialUsage.usage_type == usage_type)
        
        if start_date:
            try:
                start_dt = datetime.strptime(start_date, '%Y-%m-%d')
                query = query.filter(MaterialUsage.usage_date >= start_dt)
            except ValueError:
                pass
        
        if end_date:
            try:
                end_dt = datetime.strptime(end_date, '%Y-%m-%d')
                query = query.filter(MaterialUsage.usage_date <= end_dt)
            except ValueError:
                pass
        
        # 按使用日期倒序排列
        query = query.order_by(MaterialUsage.usage_date.desc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        records = []
        for usage in pagination.items:
            record = usage.to_dict()
            # 添加材料信息
            record.update({
                'material_code': usage.material.code,
                'material_name': usage.material.name,
                'specification': usage.material.specification,
                'unit': usage.material.unit,
                'unit_price': float(usage.material.unit_price) if usage.material.unit_price else 0
            })
            records.append(record)
        
        return jsonify({
            'records': records,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': pagination.page,
            'per_page': pagination.per_page
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取使用记录失败: {str(e)}'}), 500

@material_usage_bp.route('/<int:usage_id>', methods=['GET'])
@require_permission('material.view')
def get_usage_record(usage_id):
    """获取单个使用记录详情"""
    try:
        current_user = get_current_user()
        usage = MaterialUsage.query.get_or_404(usage_id)
        
        # 权限检查
        if current_user.role == 'user' and usage.user_id != current_user.id:
            return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager' and current_user.group_id:
            if usage.work_order and usage.work_order.group_id != current_user.group_id:
                if usage.user_id != current_user.id:
                    return jsonify({'error': '权限不足'}), 403
        
        record = usage.to_dict()
        # 添加材料信息
        record.update({
            'material_code': usage.material.code,
            'material_name': usage.material.name,
            'specification': usage.material.specification,
            'unit': usage.material.unit,
            'unit_price': float(usage.material.unit_price) if usage.material.unit_price else 0
        })
        
        return jsonify({'record': record}), 200
        
    except Exception as e:
        return jsonify({'error': f'获取使用记录失败: {str(e)}'}), 500

@material_usage_bp.route('', methods=['POST'])
@require_permission('material.edit')
def create_usage_record():
    """创建使用记录"""
    try:
        data = request.get_json()
        current_user = get_current_user()
        
        # 验证必需字段
        required_fields = ['material_id', 'quantity', 'usage_type', 'user_name', 'usage_date', 'purpose']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({'error': f'缺少必需字段: {field}'}), 400
        
        # 获取材料
        material = Material.query.get(data['material_id'])
        if not material:
            return jsonify({'error': '材料不存在'}), 404
        
        if not material.is_active:
            return jsonify({'error': '材料已停用'}), 400
        
        # 检查库存
        if data['quantity'] > material.stock_quantity:
            return jsonify({'error': '使用数量超过当前库存'}), 400
        
        # 解析使用日期
        try:
            usage_date = datetime.strptime(data['usage_date'], '%Y-%m-%d')
        except ValueError:
            return jsonify({'error': '使用日期格式错误，应为YYYY-MM-DD'}), 400
        
        # 获取工单（如果有）
        work_order = None
        if data.get('work_order_id'):
            work_order = WorkOrder.query.get(data['work_order_id'])
            if not work_order:
                return jsonify({'error': '工单不存在'}), 404
        
        # 创建使用记录
        usage = MaterialUsage(
            material_id=data['material_id'],
            work_order_id=data.get('work_order_id'),
            user_id=current_user.id,
            quantity=data['quantity'],
            usage_type=data['usage_type'],
            user_name=data['user_name'],
            usage_date=usage_date,
            purpose=data['purpose'],
            notes=data.get('notes', '')
        )
        
        # 减少库存
        material.stock_quantity -= data['quantity']
        
        db.session.add(usage)
        db.session.commit()
        
        return jsonify({
            'message': '使用记录创建成功',
            'record': usage.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建使用记录失败: {str(e)}'}), 500

@material_usage_bp.route('/<int:usage_id>', methods=['PUT'])
@require_permission('material.edit')
def update_usage_record(usage_id):
    """更新使用记录"""
    try:
        data = request.get_json()
        current_user = get_current_user()
        
        usage = MaterialUsage.query.get_or_404(usage_id)
        
        # 权限检查
        if current_user.role == 'user' and usage.user_id != current_user.id:
            return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager' and current_user.group_id:
            if usage.work_order and usage.work_order.group_id != current_user.group_id:
                if usage.user_id != current_user.id:
                    return jsonify({'error': '权限不足'}), 403
        
        material = usage.material
        old_quantity = usage.quantity
        
        # 更新数量时需要调整库存
        if 'quantity' in data and data['quantity'] != old_quantity:
            quantity_diff = data['quantity'] - old_quantity
            if quantity_diff > material.stock_quantity:
                return jsonify({'error': '库存不足'}), 400
            material.stock_quantity -= quantity_diff
        
        # 更新字段
        if 'usage_type' in data:
            usage.usage_type = data['usage_type']
        if 'user_name' in data:
            usage.user_name = data['user_name']
        if 'usage_date' in data:
            try:
                usage.usage_date = datetime.strptime(data['usage_date'], '%Y-%m-%d')
            except ValueError:
                return jsonify({'error': '使用日期格式错误，应为YYYY-MM-DD'}), 400
        if 'purpose' in data:
            usage.purpose = data['purpose']
        if 'notes' in data:
            usage.notes = data['notes']
        if 'quantity' in data:
            usage.quantity = data['quantity']
        
        db.session.commit()
        
        return jsonify({
            'message': '使用记录更新成功',
            'record': usage.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新使用记录失败: {str(e)}'}), 500

@material_usage_bp.route('/<int:usage_id>', methods=['DELETE'])
@require_permission('material.edit')
def delete_usage_record(usage_id):
    """删除使用记录"""
    try:
        current_user = get_current_user()
        usage = MaterialUsage.query.get_or_404(usage_id)
        
        # 权限检查
        if current_user.role == 'user' and usage.user_id != current_user.id:
            return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager' and current_user.group_id:
            if usage.work_order and usage.work_order.group_id != current_user.group_id:
                if usage.user_id != current_user.id:
                    return jsonify({'error': '权限不足'}), 403
        
        material = usage.material
        
        # 归还库存
        material.stock_quantity += usage.quantity
        
        db.session.delete(usage)
        db.session.commit()
        
        return jsonify({'message': '使用记录删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除使用记录失败: {str(e)}'}), 500

@material_usage_bp.route('/stats', methods=['GET'])
@require_permission('material.view')
def get_usage_stats():
    """获取使用记录统计数据"""
    try:
        current_user = get_current_user()
        
        # 构建基础查询
        query = db.session.query(MaterialUsage).join(Material).join(User)
        
        # 权限过滤
        if current_user.role == 'user':
            query = query.filter(MaterialUsage.user_id == current_user.id)
        elif current_user.role == 'manager' and current_user.group_id:
            query = query.join(WorkOrder, MaterialUsage.work_order_id == WorkOrder.id, isouter=True)
            query = query.filter(
                or_(
                    MaterialUsage.user_id == current_user.id,
                    WorkOrder.group_id == current_user.group_id,
                    MaterialUsage.work_order_id.is_(None)
                )
            )
        
        # 统计数据
        total_usage = query.count()
        total_materials = query.with_entities(MaterialUsage.material_id).distinct().count()
        total_users = query.with_entities(MaterialUsage.user_id).distinct().count()
        
        # 计算总价值
        total_value = 0
        for usage in query.all():
            unit_price = float(usage.material.unit_price) if usage.material.unit_price else 0
            total_value += usage.quantity * unit_price
        
        return jsonify({
            'total_usage': total_usage,
            'total_materials': total_materials,
            'total_users': total_users,
            'total_value': total_value
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取统计数据失败: {str(e)}'}), 500

@material_usage_bp.route('/export', methods=['GET'])
@require_permission('material.view')
def export_usage_records():
    """导出使用记录"""
    try:
        # 这里可以实现CSV或Excel导出功能
        # 暂时返回JSON格式数据
        return jsonify({'message': '导出功能待实现'}), 501
        
    except Exception as e:
        return jsonify({'error': f'导出失败: {str(e)}'}), 500